var globalNoteExchangeIndex;
var globalNoteExchangeContent;
var globalNoteExchangeCategory;
var globalNoteExchangeSearchTerms;
var globalNoteExchangePrivate;
var globalNoteExchangeCreationDate;
var globalNoteExchangeChangeDate;


function migrateData()
{
  var dom,elms,counter,d1,d2,pTxt,pElm,d1t,d2t,d1e,d2e,td1,td2;
  // we need to upgrade 3.1 datafiles. All others we overwrite

  // drop in missing files
  if(!dataFileExists(_ThunderNoteCategoriesFileName))
    createDataFile(_ThunderNoteCategoriesFileName+'.txt',_ThunderNoteCategoriesFileName);
    
  if(!dataFileExists(_ThunderNoteConfigFileName))
    createDataFile(_ThunderNoteConfigFileName+'.txt',_ThunderNoteConfigFileName);

  if(!dataFileExists(_ThunderNoteNotesFileName))
    createDataFile(_ThunderNoteNotesFileName+'.txt',_ThunderNoteNotesFileName);

  if(!dataFileExists(_ThunderNoteSyncDBFileName))
    createDataFile(_ThunderNoteSyncDBFileName+'.txt',_ThunderNoteSyncDBFileName);

  if(readCategoriesVersion()<4)
  {
    // for categories, all we need to update is the version #
    dom=readCategories();
    dom.documentElement.setAttribute('version','4.0');
    writeCategories(dom);
    alert('Updated to version 4.0 of Categories data file...');
  }

  if(readConfigVersion()<4)
  {
    // for config, we need to update the version # and remove SyncML stuff
    dom=readConfig();
    dom.documentElement.setAttribute('version','4.0');
    dom.getElementsByTagName('Sync')[0].removeChild(dom.getElementsByTagName('SyncMLServer')[0]);
    dom.getElementsByTagName('Sync')[0].removeChild(dom.getElementsByTagName('RemoteNotesFolder')[0]);
    dom.getElementsByTagName('Sync')[0].removeChild(dom.getElementsByTagName('RemoteContactsFolder')[0]);
    dom.getElementsByTagName('Sync')[0].removeChild(dom.getElementsByTagName('RemoteCalendarFolder')[0]);
    writeConfig(dom);
    alert('Updated to version 4.0 of Configuration data file...');
  }

  if(readThunderNotesVersion()<4)
  {
    // for notesm we need to update the version # and convert the date's to millis since 1970, and add the
    // private setting
    dom=readThunderNotes();
    dom.documentElement.setAttribute('version','4.0');
    elms=dom.getElementsByTagName('ThunderNote');
    for(counter=0;counter<elms.length;counter++)
    {
      d1=elms[counter].getElementsByTagName('CreationDTG')[0];
      d2=elms[counter].getElementsByTagName('UpdateDTG')[0];
      
      td1=-1;
      if(d1!=null)
        td1=createDateFromThunderNoteDateString(getXMLNodeValue(d1)).getTime();

      td2=-1;
      if(d2!=null)
        td2=createDateFromThunderNoteDateString(getXMLNodeValue(d2)).getTime();

      d1t=dom.createTextNode(td1);
      d2t=dom.createTextNode(td2);
      d1e=dom.createElement('CreationDTG');
      d2e=dom.createElement('UpdateDTG');
      d1e.appendChild(d1t);
      d2e.appendChild(d2t);
      elms[counter].replaceChild(d1e,d1);
      elms[counter].replaceChild(d2e,d2);
      pTxt=dom.createTextNode('true');
      pElm=dom.createElement('Private');
      pElm.appendChild(pTxt);
      elms[counter].appendChild(pElm);
    }
    writeThunderNotes(dom);
    alert('Updated to version 4.0 of Notes data file...');
  }
}

function getNoteContent()
{
  return(globalNoteExchangeContent);
}

function getNotePrivate()
{
  return(globalNoteExchangePrivate);
}

function getNoteCreationDate()
{
  return(globalNoteExchangeCreationDate);
}

function getNoteChangeDate()
{
  return(globalNoteExchangeChangeDate);
}

function getNoteIndex()
{
  return(globalNoteExchangeIndex);
}

function getNoteCategory()
{
  return(globalNoteExchangeCategory);
}

function getNoteSearchTerms()
{
  return(globalNoteExchangeSearchTerms);
}

function addNewNote()
{
  var tc=getCurrentTabCode();
  if(tc=='uncat') tc='-1';
  globalNoteExchangeContent='';
  globalNoteExchangeIndex='-1';
  globalNoteExchangeCategory=tc;
  globalNoteExchangeSearchTerms='';
  globalNoteExchangePrivate=true;
  globalNoteExchangeCreationDate=-1;
  globalNoteExchangeChangeDate=-1;
  var newwin=window.open(_ThunderNoteXUL,'','chrome,width=300,height=400,resizable=yes,modal=yes');
}

function showHelp()
{
  var newwin=window.open(_ThunderNoteHelpXUL,'','chrome,width=800,height=600,resizable=yes');
}

function showSyncDialog()
{
  var newwin=window.open(_ThunderNoteSyncXUL,'','chrome,width=325,height=450,resizable=yes,modal=yes');
}

function showConfig()
{
  var newwin=window.open(_ThunderNoteConfigXUL,'','chrome,width=300,height=355,resizable=yes,modal=yes');
}

function editNote(tabID)
{
  var tc=getCurrentTabCode();
  if(tc=='uncat') tc='-1';
  var listControl=document.getElementById(tabID);
  var rows;
  var selIdx;
  var removedItem;
  var e1;
  var tno
  
  if(listControl!=null)
  {
    rows=listControl.getRowCount();
    if(rows>0)
    {
      selIdx=listControl.selectedIndex;
      if(selIdx!=-1)
      {
        e1=listControl.getItemAtIndex(selIdx);
        var v=e1.value;
                
        tno=findNote(v);
        globalNoteExchangeContent=tno.title+tno.body;
        //consoleMessage('<-- EDITNODE STARTS-->');
        //consoleMessage(globalNoteExchangeContent);
        //consoleMessage(tno.body);
        //consoleMessage('<-- EDITNODE STARTS-->');
        globalNoteExchangeContent=unescape(globalNoteExchangeContent);
        globalNoteExchangeIndex=v;
        globalNoteExchangeCategory=tc;
        globalNoteExchangeSearchTerms='';
        globalNoteExchangePrivate=tno.privatenote;
        globalNoteExchangeCreationDate=tno.creationdtg;
        globalNoteExchangeChangeDate=tno.updatedtg;
        var newwin=window.open(_ThunderNoteXUL,'','chrome,width=300,height=400,resizable=yes,modal=yes');

      }
      else
        alert('There are no ThunderNotes selected to edit');
    }
    else
      alert('There are no ThunderNotes to edit');
  }
}

function deleteSelectedNote()
{
  var catSearch=getCurrentRichListBoxID();
  var listControl=document.getElementById(catSearch);
  var rows;
  var selIdx;
  var removedItem;
  var e1;
  
  if(listControl!=null)
  {
    rows=listControl.getRowCount();
    if(rows>0)
    {
      selIdx=listControl.selectedIndex;
      if(selIdx!=-1)
      {
        e1=listControl.getItemAtIndex(selIdx);
        var v=e1.value;
        
        if(confirm('Are you sure you want to delete the selected ThunderNote?'))
        {
          removeNote(v);
          listControl.clearSelection();
          for(var x=0;x<rows;x++)
          {
            var e=listControl.getItemAtIndex(x);
    
            if(e.value==v)
              listControl.removeChild(e);
          }
        }
      }
      else
        alert('There are no ThunderNotes selected to delete');
    }
    else
      alert('There are no ThunderNotes to delete');
  }
}

function removeNoteFromListForMove(idx)
{
  var catSearch=getCurrentRichListBoxID();
  var listControl=document.getElementById(catSearch);
  var noteItem;
  
  if(listControl!=null)
  {
    rows=listControl.getRowCount();
    if(rows>0)
    {
      
      for(var x=0;x<rows;x++)
      {
        var e=listControl.getItemAtIndex(x);

        if(e.value==idx)
        {
          listControl.removeChild(e);
          break;
        }
      }
    }
  }
}

function loadNotes()
{
  var dom = readThunderNotes();
  var children=dom.documentElement.childNodes;

  loadCategories();
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='ThunderNote')
      addThunderNoteFromXml(children[x]);
  }
}

function addThunderNoteFromXml(xmlNode)
{
  var children=xmlNode.childNodes;
  var title='',idx='',cat='-1';
  
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='Title')
      title=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='ApplicationNotes')
      idx=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='Category')
      cat=getXMLNodeValue(children[x]);
  }
  
  if(cat=='-1')
    cat='thundernotelist2';
  else
    cat='rtlb_'+cat;

  title=unescape(title);
  addThunderNote(title,idx,cat,cat);
}

function addThunderNote(title,idx,catIdx,tbl)
{
  var catSearch
  
  if(tbl==null)
    catSearch=getCurrentRichListBoxID();
  else
    catSearch=tbl;
  
  // thanks to http://hyperstruct.net/2006/9/30/xul-patterns-modular-interfaces
  
  // create a clone of a hidden item from the XUL
  var thunderNoteItem = document.getElementById('blueprints')
      .getElementsByAttribute('role', 'thundernote')[0].cloneNode(true);
  
  // set the value attribute
  thunderNoteItem.setAttribute('value',idx);
  
  // find the title child and set the title
  thunderNoteItem.getElementsByAttribute('role', 'title')[0]
      .setAttribute('value', title);
  
  // add it to the list    
  document.getElementById(catSearch).appendChild(thunderNoteItem);    
}

function findNote(idx)
{
  var RetVal='';
  var dom = readThunderNotes();
  var tno=new ThunderNoteObject(null);
  
  var children=dom.documentElement.childNodes;
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='ThunderNote')
    {
      tno.assignRawXml(getSerializeNode(children[x]));
      if(tno.applicationnotes==idx)
      {
        RetVal=tno;
        break;
      }
    }
  }
  
  return(RetVal);
}

function getNodeNote(xmlNode)
{
  var children=xmlNode.childNodes;
  var title='',body='';
  
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='Title')
      title=getXMLNodeValue(children[x]);
    if(children[x].nodeName=='Body')
      body=getXMLNodeValue(children[x]);
  }
  
  return(title+body);
}

function removeNote(idx)
{
  var dom = readThunderNotes();
  var found=false;
  
  var children=dom.documentElement.childNodes;
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='ThunderNote')
    {
      if(checkNodeIndex(children[x],idx,'ApplicationNotes'))
      {
        dom.documentElement.removeChild(children[x]);
        found=true;      
        break;
      }
    }
  }
  
  if(found)
  {
    writeThunderNotes(dom);
  }  
}

//function createNewNote(title,body,idx,catcode,searchTerms,dateString)
function createNewNote(title,body,idx,catcode,searchTerms,createDTG,updateDTG,privNote)
{
  var myPriv,myBody;
  
  if(privNote==null)
    myPriv='true';
  else
  {
    if(privNote==false)
      myPriv='false';
    else
      myPriv='true';
  }

  var createdate,updatedate,bdy;
  if(createDTG==null)
    createdate=-1;
  else
    createdate=createDTG;
    
  if(updateDTG==null)
    updatedate=-1;
  else
    updatedate=updateDTG;
    
  myBody=body;
  if(myBody!=null)
  {
    if(myBody.length>_ThunderNoteMaxNoteSize)
    {
      myBody=myBody.substring(0,_ThunderNoteMaxNoteSize-1); 
    }
  }

  bdy=myBody;
  if(bdy.charAt(0)!='\n')
    bdy='\n'+bdy
  
  var dom = readThunderNotes();
  var titleText=dom.createTextNode(escape(title));
  var bodyText=dom.createTextNode(escape(bdy));
  var idxText=dom.createTextNode(idx);
  var catText=dom.createTextNode(catcode);
  var stText=dom.createTextNode(escape(searchTerms));
  var dt1=dom.createTextNode(createdate);
  var dt2=dom.createTextNode(updatedate);
  var pTxt=dom.createTextNode(myPriv);

  var e=dom.createElement("ThunderNote");

  var titleElm=dom.createElement("Title");
  titleElm.appendChild(titleText);

  var bodyElm=dom.createElement("Body");
  bodyElm.appendChild(bodyText);
  
  var createElm=dom.createElement("CreationDTG");
  createElm.appendChild(dt1);
  
  var updateElm=dom.createElement("UpdateDTG");
  updateElm.appendChild(dt2);

  var idxElm=dom.createElement("ApplicationNotes");
  idxElm.appendChild(idxText);
  
  var catElm=dom.createElement("Category");
  catElm.appendChild(catText);

  var stElm=dom.createElement("SearchTerms");
  stElm.appendChild(stText);

  var pElm=dom.createElement("Private");
  pElm.appendChild(pTxt);
  
  e.appendChild(titleElm);
  e.appendChild(bodyElm);
  e.appendChild(createElm);
  e.appendChild(updateElm);
  e.appendChild(idxElm);
  e.appendChild(catElm);
  e.appendChild(stElm);
  e.appendChild(pElm);

  dom.documentElement.appendChild(e);

  addThunderNote(title,idx,catcode,null);

  writeThunderNotes(dom);
}

function modifyExistingNote(title,body,idx,catCode,searchTerms,updateList,createDTG,updateDTG,privNote)
{
  var catSearch='rtlb_'+catCode;
  if(catSearch=='rtlb_-1' || catSearch=='rtlb_uncat')  catSearch='thundernotelist2';

  var listControl=document.getElementById(catSearch);
  var rows=listControl.getRowCount();
  var myPriv;
  
  if(privNote==null)
    myPriv='true';
  else
  {
    if(privNote==false)
      myPriv='false';
    else
      myPriv='true';
  }

  var createdate,updatedate,bdy,myBody;
  if(createDTG==null)
    createdate=-1;
  else
    createdate=createDTG;
    
  if(updateDTG==null)
    updatedate=-1;
  else
    updatedate=updateDTG;

  var catCode2;
  
  if(catCode=='uncat')
    catCode2='-1';
  else
    catCode2=catCode;

  myBody=body;
  if(myBody!=null)
  {
    if(myBody.length>_ThunderNoteMaxNoteSize)
    {
      myBody=myBody.substring(0,_ThunderNoteMaxNoteSize-1); 
    }
  }
  
  bdy=myBody;
  if(bdy.charAt(0)!='\n')
    bdy='\n'+bdy
    
  var dom = readThunderNotes();
  var titleText=dom.createTextNode(escape(title));
  var bodyText=dom.createTextNode(escape(bdy));
  var idxText=dom.createTextNode(idx);
  var catText=dom.createTextNode(catCode2);
  var stText=dom.createTextNode(escape(searchTerms));
  var dt1=dom.createTextNode(createdate);
  var dt2=dom.createTextNode(updatedate);
  var pTxt=dom.createTextNode(myPriv);
  
  var e=dom.createElement("ThunderNote");

  var titleElm=dom.createElement("Title");
  titleElm.appendChild(titleText);

  var bodyElm=dom.createElement("Body");
  bodyElm.appendChild(bodyText);
  
  var createElm=dom.createElement("CreationDTG");
  
  var updateElm=dom.createElement("UpdateDTG");
  updateElm.appendChild(dt2);

  var idxElm=dom.createElement("ApplicationNotes");
  idxElm.appendChild(idxText);

  var catElm=dom.createElement("Category");
  catElm.appendChild(catText);

  var stElm=dom.createElement("SearchTerms");
  stElm.appendChild(stText);
  
  var pElm=dom.createElement("Private");
  pElm.appendChild(pTxt);

  var found=false,done=false;
  
  var children=dom.documentElement.childNodes;
  for(var x=0;x<children.length;x++)
  {
    if(children[x].nodeName=='ThunderNote')
    {
      if(checkNodeIndex(children[x],idx,'ApplicationNotes'))
      {
        dt2=getNodeCreationDTG(children[x]);
        dt2Text=dom.createTextNode(dt2)
        createElm.appendChild(dt2Text);
        e.appendChild(titleElm);
        e.appendChild(bodyElm);
        e.appendChild(createElm);
        e.appendChild(updateElm);
        e.appendChild(idxElm);
        e.appendChild(catElm);
        e.appendChild(stElm);
        e.appendChild(pElm);
        
        dom.documentElement.replaceChild(e,children[x]);
        
        found=true;      
        break;
      }
    }
  }

  if(found)
  {
    
    writeThunderNotes(dom);
    
    // there should be an existing note but its possible the user opened the edit window
    // and then deleted the note prior to saving
    if(updateList)
    {
      if(rows>0)
      {
        for(var x=0;x<rows;x++)
        {
          var e=listControl.getItemAtIndex(x);
  
          if(e.value==idx)
          {
            // found right child node
            var children=e.childNodes;
            for(var y=0;y<children.length;y++)
            {
              if(children[y].nodeName=='label')
              {
                children[y].setAttribute('value',title);
                done=true;
                break;
              }
            }
            
            if(done)
              break;
          }
        }
      }
      else
        addThunderNote(title,idx,catCode,null); 
    }
  }
}

function addDateElement(d,e)
{
  var x;
  var r='';
  
  switch(e)
  {
    case 'Month':
      x=d.getMonth();
      break;
    case 'Day':
      x=d.getDate();
      break;
    case 'Year':
      x=d.getFullYear();
      break;
    case 'Hours':
      x=d.getHours();
      break;
    case 'Minutes':
      x=d.getMinutes();
      break;
    case 'Seconds':
      x=d.getSeconds();
      break;
  }
  
  r=r+x;
  return(r);
}

function getNodeCreationDTG(xmlNode)
{
  return(getNamedNodeValue(xmlNode,'CreationDTG'));
}

function onMainKeyPress(e)
{
  
  // courtesy of http://users.fmg.uva.nl/rgrasman/jscript/2005/07/capturing-escape-esc-key-in-javascript.html
  var kC  = (window.event) ?    // MSIE or Firefox?
             event.keyCode : e.keyCode;
  var Esc = (window.event) ?   
            27 : e.DOM_VK_DELETE // MSIE : Firefox
  if(kC==Esc)
  {
    deleteSelectedNote();
    return(false);
  }
  
  return(true);
}
